package com.rc.saas.tenant.controller.channel;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.model.channel.RcChannelApply;
import com.rc.saas.tenant.model.channel.RcChannelLevelSetting;
import com.rc.saas.tenant.model.channel.RcChannelLevelSettingExample;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseLevelSetting;
import com.rc.saas.tenant.model.msg.TenantReceive;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.channel.RcChannelLevelSettingService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/channel/level")
public class ChannelLevelController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RcChannelLevelSettingService channelLevelSettingService;

    @Autowired
    private UploadComponent uploadComponent;

    @RequestMapping("/index")
    public String index() {
        return "/templates/channel/channelLevel";
    }

    @ResponseBody
    @RequestMapping("/listPageChannelLevel")
    public WebPageInfo listPageChannelLevel(String levelName, Integer pageNo, Integer pageSize) {
        PageInfo<RcChannelLevelSetting> pageInfo = channelLevelSettingService.listPageChannelLevel(levelName, pageNo, pageSize);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出渠道商等级列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(String levelName,
                            @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageInfo<RcChannelLevelSetting> pageInfo = channelLevelSettingService.listPageChannelLevel(levelName, pageNo, pageSize);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("渠道商等级列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcChannelLevelSetting.class).sheet("渠道商等级列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出渠道商等级列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    @RequestMapping("/add")
    public String add() {
        return "/templates/channel/addChannelLevel";
    }

    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") String id) {
        RcChannelLevelSetting channelLevelSetting = channelLevelSettingService.selectByPrimaryKey(id);
        model.addAttribute("channelLevelSetting",channelLevelSetting);
        return "/templates/channel/editChannelLevel";
    }

    @ResponseBody
    @RequestMapping("/delete")
    public TResponse del(String id) {
        channelLevelSettingService.deleteByPrimaryKey(id);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/addChannelLevel")
    public TResponse addChannelLevel(RcChannelLevelSetting channelLevel,
                                     @RequestParam(value = "file1", required = false) MultipartFile file1) {

        RcChannelLevelSettingExample example = new RcChannelLevelSettingExample();
        example.createCriteria().andChannelLevelEqualTo(channelLevel.getLevelTypeName());
        List<RcChannelLevelSetting> list = channelLevelSettingService.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return TResponse.FAIL("失败：该等级已存在");
        }

        TenantUser user = ShiroUtils.getSessionUser();
        if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
            channelLevel.setLevelLogo(imgUrl);
        }
        channelLevel.setChannelLevel(channelLevel.getLevelTypeName());
        channelLevelSettingService.insertSelective(channelLevel);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/updateChannelLevel")
    public TResponse updateChannelLevel(RcChannelLevelSetting channelLevel,
                                     @RequestParam(value = "file1", required = false) MultipartFile file1) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
            channelLevel.setLevelLogo(imgUrl);
        }
        channelLevelSettingService.updateByPrimaryKeySelective(channelLevel);
        return TResponse.SUCCESS();
    }


}
